package cn.wizzer.app.web.modules.controllers.platform.bus;

import cn.wizzer.app.bus.modules.models.BusinessFileInfo;
import cn.wizzer.app.bus.modules.models.YJbxx;
import cn.wizzer.app.bus.modules.models.YJbxxLzxx;
import cn.wizzer.app.bus.modules.services.BusinessFileInfoService;
import cn.wizzer.app.bus.modules.services.YJbxxLcxxService;
import cn.wizzer.app.bus.modules.services.YJbxxLzxxService;
import cn.wizzer.app.bus.modules.services.YJbxxService;
import cn.wizzer.app.sys.modules.models.Sys_unit;
import cn.wizzer.app.sys.modules.models.Sys_user;
import cn.wizzer.app.sys.modules.services.SysDictService;
import cn.wizzer.app.sys.modules.services.SysUnitService;
import cn.wizzer.app.sys.modules.services.SysUserService;
import cn.wizzer.app.web.commons.base.Globals;
import cn.wizzer.app.web.commons.doc.DocUtils;
import cn.wizzer.app.web.commons.slog.annotation.SLog;
import cn.wizzer.app.web.commons.utils.DateUtil;
import cn.wizzer.app.web.commons.utils.StringUtil;
import cn.wizzer.app.web.modules.controllers.open.file.UploadController;
import cn.wizzer.framework.base.Result;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.dao.Cnd;
import org.nutz.dao.Sqls;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.lang.Times;
import org.nutz.lang.util.NutMap;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import org.nutz.trans.Atom;
import org.nutz.trans.Trans;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.sql.Connection;
import java.util.*;


/**
 * 样品移交  虞秀斌  2019-11
 */
@IocBean
@At("/platform/bus/ypxx/transfer")
public class TransferController {
    private static final Log log = Logs.get();
    @Inject
    private YJbxxService yjbxxService;
    @Inject
    private YJbxxLzxxService yjbxxlzxxservice;
    @Inject
    private YJbxxLcxxService yjbxxlcxxservice;
    @Inject
    private SysDictService sysDictService;
    @Inject
    private SysUserService sysUserService;
    @Inject
    private SysUnitService sysUnitService;
    @Inject
    private BusinessFileInfoService businessFileInfoService;

    @At("/")
    @Ok("beetl:/platform/bus/ypxx/transfer/index.html")
    @RequiresPermissions("bus.ypxx.transfer")
    public void index(HttpServletRequest req) {
        req.setAttribute("jylxMap", JSONObject.fromObject(sysDictService.getCodeMap("jylx")));
        req.setAttribute("lzztMap", JSONObject.fromObject(sysDictService.getCodeMap("lzzt")));
        //req.setAttribute("lzztOptions", JSONArray.fromObject(sysDictService.dictCodeTree("lzzt")));
        //req.setAttribute("userId", StringUtil.getPlatformUid());
        //req.setAttribute("type", type);//transferred 待移交 //toReceived 待接收 adReceived 已接收
    }

    @At
    @Ok("json:{locked:'password|salt',ignoreNull:false}")
    @RequiresPermissions("bus.ypxx.transfer.list")
    public Object data(@Param("searchKeyword") String searchKeyword,@Param("type") String type,@Param("pageNumber") int pageNumber,
                       @Param("pageSize") int pageSize, @Param("pageOrderName") String pageOrderName, @Param("pageOrderBy") String pageOrderBy) {
        try {
            //String sql ="SELECT (select status from y_jbxx_lzxx lzxx where lzxx.jbxxId = jbxx.id and lzxx.lzzt = jbxx.lzzt and lzxx.nextsprIds =jbxx.jsr) status,jbxx.id,jbxx.lzzt,jbxx.lczt, jbxx.ypbh, jbxx.ypmc, jbxx.jylx, jbxx.jyks, jbxx.wtdw, jbxx.ggxh, jbxx.scrqpc, jbxx.sb, jbxx.wcqx,jbxx.jsr,jbxx.opBy" +
                    //" FROM y_jbxx jbxx where 1=1 and jbxx.lczt>0 and jbxx.delflag = 0 ";
            String sql =" select jbxx.*,u.username from y_jbxx  jbxx left join sys_user u on u.id=jbxx.opBy where 1=1 and jbxx.lczt>0 and jbxx.delflag = 0 ";
            String countSql = " select count(1) from y_jbxx  jbxx where 1=1 and jbxx.lczt>0 and jbxx.delflag = 0 ";

            if (Strings.isNotBlank(searchKeyword)) {
                sql+= " and (jbxx.ypbh like '%"+searchKeyword+"%' or jbxx.ypmc like '%"+searchKeyword+"%')";
               // countSql+= " and (jbxx.ypbh like '%"+searchKeyword+"%' or jbxx.ypmc like '%"+searchKeyword+"%')";
            }
            if(!Strings.isNotBlank(type)){
                return Result.error("没有权限！");
            }
            String dateScope = StringUtil.dataScopeFilter("jbxx");
            //待办数量
            int transferredCount = yjbxxService.count(Sqls.create(countSql+dateScope+" and jbxx.lzzt = 0"));
            int toReceivedCount = yjbxxService.count(Sqls.create(countSql+" and jbxx.jsr = '"+StringUtil.getPlatformUid()+"' and jbxx.lzzt in (1,2) and jbxx.status = 0"));
            int adReceivedCount = yjbxxService.count(Sqls.create(countSql+" and jbxx.jsr = '"+StringUtil.getPlatformUid()+"' and jbxx.lzzt in (1,2) and (jbxx.status = 1 or jbxx.status = '-1') "));

            if (Strings.isNotBlank(type)&&type.equals("transferred")) {//查询当前人自己登记的，待移交的样品
               sql+= dateScope+" and jbxx.lzzt = 0";
            }
            if (Strings.isNotBlank(type)&&type.equals("toReceived")) {//已移交和已退样 查询接收人是当前人，并且status是0的样品
               sql+= " and jbxx.jsr = '"+StringUtil.getPlatformUid()+"' and jbxx.lzzt in (1,2) and jbxx.status = 0 ";
            }
            if (Strings.isNotBlank(type)&&type.equals("adReceived")) {//已移交和已退样 查询接收人是当前人，并且status是1确认,-1已退回的样品
                sql+= " and jbxx.jsr = '"+StringUtil.getPlatformUid()+"' and jbxx.lzzt in (1,2) and (jbxx.status = 1 or jbxx.status = '-1')";
            }
            if (Strings.isNotBlank(type)&&type.equals("adReturn")) {//已归还
                sql+= dateScope+" and jbxx.lzzt =3 ";
            }
            if (Strings.isNotBlank(type)&&type.equals("adWithdrawal")) {//当前人已退样  查询流转信息中有退样人员是自己的，并且并且status是1确认或待接收,-1拒收的样品
                sql+= " and jbxx.id in (select l.jbxxId from y_jbxx_lzxx l where  l.jbxxId = jbxx.id and l.lzzt = 2 and (l.status=1 or l.status=0) and l.opBy ='"+StringUtil.getPlatformUid()+"')  ";
            }
            if (Strings.isNotBlank(type)&&type.equals("dispose")) {//已自行处置
                sql+= " and (( 1=1 "+dateScope+") or jbxx.jsr='"+StringUtil.getPlatformUid()+"') and jbxx.lzzt =4 ";
            }
            if (Strings.isNotBlank(pageOrderName) && Strings.isNotBlank(pageOrderBy)) {
                if ("ascending".equalsIgnoreCase(pageOrderBy)) {
                    sql+= " order by jbxx."+pageOrderName+" asc,jbxx.opAt desc ";
                } else {
                    sql+= " order by jbxx."+pageOrderName+" desc,jbxx.opAt desc ";
                }
            }else{
                sql+= " order by jbxx.opAt desc ";
            }
            NutMap map =  NutMap.NEW();
            map.addv("listPages",yjbxxService.listPageMap(pageNumber,pageSize, Sqls.create(sql)));
            map.addv("transferredCount",transferredCount);
            map.addv("toReceivedCount",toReceivedCount);
            map.addv("adReceivedCount",adReceivedCount);
            return Result.success().addData(map);
        } catch (Exception e) {
            return Result.error();
        }
    }

    @At("/toDetail/?")
    @Ok("json")
    @RequiresAuthentication
    public Object toDetail(String id) {
        YJbxx obj = yjbxxService.fetch(id);
        obj.setYjsj(DateUtil.getDateTime());
        obj.setYjr(StringUtil.getPlatformUid());//
        Map map = new HashMap();
        map.put("obj",JSONObject.fromObject(obj));

        List<NutMap> treeList = new ArrayList<>();
        List<Sys_user> list = sysUserService.listEntity(Sqls.create("select * from sys_user where unitid in ('"+obj.getJyksbh().replace(",","','")+"') and delFlag=0 and disabled=0 "));
        for (Sys_user sysUser : list) {
            NutMap map1 = NutMap.NEW().addv("value", sysUser.getId()).addv("label", sysUser.getUsername());
            treeList.add(map1);
        }
        map.put("userOptions",JSONArray.fromObject(treeList));

        //获取最新的当前人流转信息
        List<YJbxxLzxx> listLz = yjbxxlzxxservice.listEntity(Sqls.create("select * from y_jbxx_lzxx where jbxxId ='"+id+"' and nextsprIds='"+StringUtil.getPlatformUid()+"' order by opAt desc LIMIT 1"));
        if(listLz.size()>0){
            map.put("lzxxObj",listLz.get(0));
            map.put("fqr",sysUserService.fetch(listLz.get(0).getOpBy()).getUsername());
        }
        return Result.success().addData(map);
    }

    @At
    @Ok("json")
    @RequiresAuthentication
    @SLog(tag = "移交样品", msg = "样品:${args[0].ypbh}")
    public Object lzxxDo(@Param("..") YJbxx obj,@Param("..") YJbxxLzxx lzxxObj,@Param("buType") String buType,@Param("oldLzxxId") String oldLzxxId) {
        try {
            YJbxx jbxx =  yjbxxService.fetch(obj.getId());
            String lzzt = "0";
            String status = "0";
            if(buType.equals("yijiao")){
                jbxx.setYjsl(obj.getYjsl());
                jbxx.setSfty(obj.getSfty());
                jbxx.setTyzt(obj.getTyzt());
                jbxx.setYjsj(obj.getYjsj());
                jbxx.setJsr(lzxxObj.getNextsprIds());

                lzxxObj.setNumber(obj.getYjsl());
                lzxxObj.setLzAt(obj.getYjsj());
                lzzt = "1";

                if(StringUtils.isNotBlank(oldLzxxId)){
                    YJbxxLzxx lzxx = yjbxxlzxxservice.fetch(oldLzxxId);
                    if(StringUtils.isNotBlank(lzxxObj.getJywcrq())){
                        lzxx.setJywcrq(lzxxObj.getJywcrq());
                    }
                    if(StringUtils.isNotBlank(lzxxObj.getByczqk())){
                        lzxx.setByczqk(lzxxObj.getByczqk());
                    }
                    yjbxxlzxxservice.updateIgnoreNull(lzxx);
                }
            }else if(buType.equals("tuiyang")){
                jbxx.setBgbh(obj.getBgbh());
                if(jbxx.getSfty().equals("1")){//直接自行处置
                    lzzt = "4";
                    status = "1";
                }else{
                    jbxx.setTysl(obj.getTysl());
                    jbxx.setYjsj(obj.getYjsj());
                    jbxx.setJsr(obj.getOpBy());
                    lzxxObj.setNextsprIds(obj.getOpBy());
                    lzxxObj.setLzAt(obj.getYjsj());
                    Sys_user user = sysUserService.fetch(obj.getOpBy());
                    lzxxObj.setNextspr(user.getUsername());
                    lzxxObj.setNumber(obj.getTysl());
                    lzzt = "2";
                }

                if(StringUtils.isNotBlank(oldLzxxId)){
                    YJbxxLzxx lzxx = yjbxxlzxxservice.fetch(oldLzxxId);
                    if(StringUtils.isNotBlank(lzxxObj.getJywcrq())){
                        //lzxx.setJywcrq(lzxxObj.getJywcrq());
                        jbxx.setJywcrq(lzxxObj.getJywcrq());
                    }
                    if(StringUtils.isNotBlank(lzxxObj.getByczqk())){
                        //lzxx.setByczqk(lzxxObj.getByczqk());
                        jbxx.setByczqk(lzxxObj.getByczqk());
                    }
                    yjbxxlzxxservice.updateIgnoreNull(lzxx);
                }
            }else if(buType.equals("guihuan")){
                jbxx.setGhsl(obj.getGhsl());
                lzxxObj.setNumber(obj.getGhsl());
                lzzt = "3";
                status = "1";
            }
            jbxx.setLzzt(lzzt);
            jbxx.setStatus(status);
            lzxxObj.setLzzt(lzzt);
            lzxxObj.setStatus(status);
            lzxxObj.setYpbh(jbxx.getYpbh());
            lzxxObj.setJbxxId(jbxx.getId());
            lzxxObj.setOpBy(StringUtil.getPlatformUid());
            lzxxObj.setOpAt(Times.getTS());

            lzxxObj.setJywcrq("");
            lzxxObj.setByczqk("");
            Trans.exec(Connection.TRANSACTION_SERIALIZABLE, new Atom() {
                public void run() {
                    yjbxxService.updateIgnoreNull(jbxx);
                    yjbxxlzxxservice.insert(lzxxObj);
                    yjbxxlzxxservice.clearCache();
                    yjbxxlcxxservice.clearCache();
                }
            });
            return Result.success("操作成功！");
        } catch (Exception e) {
            return Result.error("system.error");
        }
    }

    @At
    @Ok("json")
    @RequiresAuthentication
    @SLog(tag = "接收样品", msg = "样品:${args[0].ypbh}")
    public Object jsDo(@Param("..") YJbxxLzxx lzxxObj,@Param("fqr") String fqr) {
        try {
            YJbxxLzxx lzxx = yjbxxlzxxservice.fetch(lzxxObj.getId());
            YJbxx jbxx = yjbxxService.fetch(lzxxObj.getJbxxId());
            if(lzxxObj.getStatus().equals("1")){
                lzxx.setStatus(lzxxObj.getStatus());
                lzxx.setStatusAt(lzxxObj.getStatusAt());
                jbxx.setStatus(lzxxObj.getStatus());
                Trans.exec(Connection.TRANSACTION_SERIALIZABLE, new Atom() {
                    public void run() {
                        yjbxxService.updateIgnoreNull(jbxx);
                        yjbxxlzxxservice.updateIgnoreNull(lzxx);
                        yjbxxlzxxservice.clearCache();
                    }
                });
            }else if(lzxxObj.getStatus().equals("-1")){
                //更新当前流程的状态
                lzxx.setStatus(lzxxObj.getStatus());
                lzxx.setStatusAt(lzxxObj.getStatusAt());
                lzxx.setJsbz(lzxxObj.getSpyj());

                jbxx.setStatus(lzxxObj.getStatus());
                jbxx.setJsr(lzxxObj.getOpBy());//退回接收人是发起人

                lzxxObj.setStatus("");
                lzxxObj.setStatusAt("");
                lzxxObj.setYpbh(jbxx.getYpbh());
                lzxxObj.setJbxxId(jbxx.getId());
                lzxxObj.setLzAt(DateUtil.getDateTime());
                lzxxObj.setJhwcqx("");
                lzxxObj.setNextsprIds(lzxxObj.getOpBy());//退回接收人是发起人
                lzxxObj.setNextspr(fqr);
                lzxxObj.setOpBy(StringUtil.getPlatformUid());
                lzxxObj.setOpAt(Times.getTS());

                //查询上一步的状态
                String lzzt = "0";
                List<YJbxxLzxx> listLz = yjbxxlzxxservice.listEntity(Sqls.create("select * from y_jbxx_lzxx where jbxxId ='"+lzxxObj.getJbxxId()+"' and status!='-1'  order by opAt desc LIMIT 0,1"));
                if(listLz.size()>0){
                    lzzt = listLz.get(0).getLzzt();
                }
                lzxxObj.setLzzt(lzzt);//退回状态-1
                jbxx.setLzzt(lzzt);

                Trans.exec(Connection.TRANSACTION_SERIALIZABLE, new Atom() {
                    public void run() {
                        yjbxxService.updateIgnoreNull(jbxx);
                        //yjbxxlzxxservice.insert(lzxxObj);
                        yjbxxlzxxservice.updateIgnoreNull(lzxx);
                        yjbxxlzxxservice.clearCache();
                        yjbxxlcxxservice.clearCache();
                    }
                });
            }

            return Result.success("操作成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("system.error");
        }
    }

    @At("/createCirculation/?")
    @Ok("json")
    @RequiresAuthentication
    @SLog(tag = "流转单", msg = "")
    public Object createAgreement(String id) {
        try {
            YJbxx obj = yjbxxService.fetch(id);

            //获取到移交、退样的流程，此两个流程需要内部流转单
            List<YJbxxLzxx> lzList = yjbxxlzxxservice.listEntity(Sqls.create("select * from y_jbxx_lzxx where jbxxId ='"+id+"' and lzzt in (1,2) and status = '1' and delFlag=0  order by opAt asc "));

            //检查数据完整性
            if(StringUtils.isEmpty(obj.getJyksbh())||StringUtils.isEmpty(obj.getJyks())||StringUtils.isEmpty(obj.getZh())||StringUtils.isEmpty(obj.getYpbh())||StringUtils.isEmpty(obj.getYpmc())||StringUtils.isEmpty(obj.getJylx())||StringUtils.isEmpty(obj.getYplx())){
                return Result.error("数据不完整，无法生成流转单");
            }
            //获取流转单模板路径
            BusinessFileInfo agreementTemplate = businessFileInfoService.fetch(Cnd.where("delFlag", "=", "0").and("infoName", "=", "流转单").and("productType","like","%"+obj.getYplx()+"%").and("disabled","=",false));
            if(agreementTemplate==null){
                return Result.error("请上传样品流转单模板后再生成流转单！");
            }
            String uploadPath = this.getUploadPathConfig();
            String demoAgreement = uploadPath+agreementTemplate.getFilePath();//封面和首页内容模板路径

            //获取生成的流转单路径
            String date= DateUtil.format(new Date(), "yyyy")+"/"+DateUtil.format(new Date(), "MM")+"/"+DateUtil.format(new Date(), "dd");
            String fileName = obj.getId()+"lzd";
            String newAgreementPath = "/circulation/" + date + "/" + fileName+".docx";
            String newAgreement = uploadPath+newAgreementPath;//生成报告路径

            BusinessFileInfo oldReport = businessFileInfoService.fetch(Cnd.where("delFlag", "=", "0").and("fileName", "=", fileName));

            Trans.exec(Connection.TRANSACTION_SERIALIZABLE, new Atom() {
                public void run() {
                    if(oldReport!=null){
                        //先删除历史的文件
                        File old_report_file = new File(uploadPath+oldReport.getFilePath());
                        old_report_file.delete();
                        if (old_report_file.exists()) {
                            if (old_report_file.isFile()) {//boolean isFile():测试此抽象路径名表示的文件是否是一个标准文件。
                                old_report_file.delete();
                            }
                        }
                        businessFileInfoService.delete(oldReport.getId());
                    }
                }
            });

            int count = 1;
            //List<Map<String, String>> listMap = new ArrayList<>();
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("PL1_cydbh",StringUtils.isEmpty(obj.getCydbh())||obj.getCydbh().equals("/")?"":obj.getCydbh());
            map.put("PL2_cydbh",StringUtils.isEmpty(obj.getCydbh())||obj.getCydbh().equals("/")?"":obj.getCydbh());

            map.put("PL1_ypbh", StringUtils.isEmpty(obj.getYpbh()) ? "" : obj.getYpbh());
            map.put("PL2_ypbh", StringUtils.isEmpty(obj.getYpbh()) ? "" : obj.getYpbh());
            map.put("PL1_ypmc", StringUtils.isEmpty(obj.getYpmc()) ? "" : obj.getYpmc());
            map.put("PL2_ypmc", StringUtils.isEmpty(obj.getYpmc()) ? "" : obj.getYpmc());
            map.put("PL1_ggxh", StringUtils.isEmpty(obj.getGgxh()) ? "" : obj.getGgxh());
            map.put("PL2_ggxh", StringUtils.isEmpty(obj.getGgxh()) ? "" : obj.getGgxh());
            map.put("PL1_wtdw", StringUtils.isEmpty(obj.getWtdw()) ? "" : obj.getWtdw());
            map.put("PL2_wtdw", StringUtils.isEmpty(obj.getWtdw()) ? "" : obj.getWtdw());
            map.put("PL1_ypdj", StringUtils.isEmpty(obj.getYpdj()) ? "" : obj.getYpdj());
            map.put("PL2_ypdj", StringUtils.isEmpty(obj.getYpdj()) ? "" : obj.getYpdj());
            String jylx = getCodes(obj.getJylx(),"jylx");
            map.put("PL1_jylx", jylx);
            map.put("PL2_jylx", jylx);
            map.put("PL1_ypzt", StringUtils.isEmpty(obj.getYpzt()) ? "" : obj.getYpzt());
            map.put("PL2_ypzt", StringUtils.isEmpty(obj.getYpzt()) ? "" : obj.getYpzt());
            map.put("PL1_wcqx", StringUtils.isEmpty(obj.getWcqx()) ? "" : DateUtil.StringFormat(obj.getWcqx(), "yyyy年MM月dd日"));
            map.put("PL2_wcqx", StringUtils.isEmpty(obj.getWcqx()) ? "" : DateUtil.StringFormat(obj.getWcqx(), "yyyy年MM月dd日"));
            map.put("PL1_jyyj", StringUtils.isEmpty(obj.getJyyj()) ? "" : obj.getJyyj());
            map.put("PL2_jyyj", StringUtils.isEmpty(obj.getJyyj()) ? "" : obj.getJyyj());
            map.put("PL1_jyxm", StringUtils.isEmpty(obj.getJyxm()) ? "" : obj.getJyxm());
            map.put("PL2_jyxm", StringUtils.isEmpty(obj.getJyxm()) ? "" : obj.getJyxm());
            map.put("PL1_jywcrq", StringUtils.isEmpty(obj.getJywcrq()) ? "" : DateUtil.StringFormat(obj.getJywcrq(), "yyyy年MM月dd日"));
            map.put("PL2_jywcrq", StringUtils.isEmpty(obj.getJywcrq()) ? "" : DateUtil.StringFormat(obj.getJywcrq(), "yyyy年MM月dd日"));
            map.put("PL1_byczqk", StringUtils.isEmpty(obj.getByczqk()) ? "" : obj.getByczqk());
            map.put("PL2_byczqk", StringUtils.isEmpty(obj.getByczqk()) ? "" : obj.getByczqk());
            map.put("PL1_bgbh", StringUtils.isEmpty(obj.getBgbh()) ? "" : obj.getBgbh());
            map.put("PL2_bgbh", StringUtils.isEmpty(obj.getBgbh()) ? "" : obj.getBgbh());

            if(lzList.size() > 0) {
                YJbxxLzxx lz = lzList.get(0);
                map.put("PL1_ypsl", StringUtils.isEmpty(lz.getNumber())?"":lz.getNumber()+(StringUtils.isEmpty(obj.getUnit())?"":obj.getUnit()));
                map.put("PL2_ypsl", StringUtils.isEmpty(lz.getNumber())?"":lz.getNumber()+(StringUtils.isEmpty(obj.getUnit())?"":obj.getUnit()));
                map.put("PL1_jsyprq", StringUtils.isEmpty(lz.getStatusAt()) ? "" : DateUtil.StringFormat(lz.getStatusAt(), "yyyy年MM月dd日"));
                map.put("PL2_jsyprq", StringUtils.isEmpty(lz.getStatusAt()) ? "" : DateUtil.StringFormat(lz.getStatusAt(), "yyyy年MM月dd日"));
                map.put("PL1_bz", StringUtils.isEmpty(lz.getSpyj()) ? "" : lz.getSpyj());
                map.put("PL2_bz", StringUtils.isEmpty(lz.getSpyj()) ? "" : lz.getSpyj());
            /*if (StringUtils.isNotBlank(obj.getOpBy())) {
                Sys_user slrUser = sysUserService.fetch(obj.getOpBy());
                String fileId = slrUser.getFileId();
                if (!StringUtils.isEmpty(fileId)) {
                    BusinessFileInfo signatureImage = businessFileInfoService.fetch(fileId);
                    map.put("PL1_jsr", uploadPath + signatureImage.getFilePath());
                }
            }*/
                if (StringUtils.isNotBlank(lz.getNextsprIds())) {
                    Sys_user slrUser = sysUserService.fetch(lz.getNextsprIds());
                    String fileId = slrUser.getFileId();
                    if (!StringUtils.isEmpty(fileId)) {
                        BusinessFileInfo signatureImage = businessFileInfoService.fetch(fileId);
                        map.put("PL1_jsr", uploadPath + signatureImage.getFilePath());
                        map.put("PL2_jsr", uploadPath + signatureImage.getFilePath());
                    }
                }
            }
            DocUtils.FileToFile2(demoAgreement,newAgreement,map,new ArrayList<>());

            BusinessFileInfo report = new BusinessFileInfo();
            report.setInfoName(fileName);
            report.setInfoVersion(date);
            report.setInfoType("report");
            report.setRemark("");
            report.setOperatorName(StringUtil.getPlatformUsername());
            report.setFileType(".docx");
            report.setDisabled(false);
            report.setFilePath(newAgreementPath);
            report.setFileName(fileName);
            report.setFileBeforeName( fileName+".docx");
            report.setFileUrl(newAgreement);
            businessFileInfoService.insert(report);
            return Result.success("生成成功！").addData(newAgreement);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("system.error");
        }
    }



    @At("/createCirculationOld/?")
    @Ok("json")
    @RequiresAuthentication
    //@RequiresPermissions("bus.ypxx.transfer.circulation")
    //已废弃该方法，不删除保留
    @SLog(tag = "流转单", msg = "")
    public Object createAgreementOld(String id) {
        try {
            YJbxx obj = yjbxxService.fetch(id);

            //获取到移交、退样的流程，此两个流程需要内部流转单
            List<YJbxxLzxx> lzList = yjbxxlzxxservice.listEntity(Sqls.create("select * from y_jbxx_lzxx where jbxxId ='"+id+"' and lzzt in (1,2) and status = '1'  order by opAt asc "));

            //检查数据完整性
            if(StringUtils.isEmpty(obj.getJyksbh())||StringUtils.isEmpty(obj.getJyks())||StringUtils.isEmpty(obj.getZh())||StringUtils.isEmpty(obj.getYpbh())||StringUtils.isEmpty(obj.getYpmc())||StringUtils.isEmpty(obj.getJylx())||StringUtils.isEmpty(obj.getYplx())){
                return Result.error("数据不完整，无法生成委托协议书");
            }
            //获取流转单模板路径
            BusinessFileInfo agreementTemplate = businessFileInfoService.fetch(Cnd.where("delFlag", "=", "0").and("infoName", "=", "流转单").and("productType","like","%"+obj.getYplx()+"%").and("disabled","=",false));
            if(agreementTemplate==null){
                return Result.error("请上传样品流转单模板后再生成流转单！");
            }
            String uploadPath = this.getUploadPathConfig();
            String demoAgreement = uploadPath+agreementTemplate.getFilePath();//封面和首页内容模板路径

            //获取生成的流转单路径
            String date= DateUtil.format(new Date(), "yyyy")+"/"+DateUtil.format(new Date(), "MM")+"/"+DateUtil.format(new Date(), "dd");
            String fileName = obj.getId()+"lzd";
            String newAgreementPath = "/circulation/" + date + "/" + fileName+".docx";
            String newAgreement = uploadPath+newAgreementPath;//生成报告路径

            BusinessFileInfo oldReport = businessFileInfoService.fetch(Cnd.where("delFlag", "=", "0").and("fileName", "=", fileName));

            Trans.exec(Connection.TRANSACTION_SERIALIZABLE, new Atom() {
                public void run() {
                    if(oldReport!=null){
                        //先删除历史的文件
                        File old_report_file = new File(uploadPath+oldReport.getFilePath());
                        old_report_file.delete();
                        if (old_report_file.exists()) {
                            if (old_report_file.isFile()) {//boolean isFile():测试此抽象路径名表示的文件是否是一个标准文件。
                                old_report_file.delete();
                            }
                        }
                        businessFileInfoService.delete(oldReport.getId());
                    }
                }
            });

            int count = 1;
            List<Map<String, String>> listMap = new ArrayList<>();
            for(YJbxxLzxx lz : lzList){
                Map<String, String> map = new HashMap<String, String>();
                map.put("PL1_ypbh", StringUtils.isEmpty(obj.getYpbh())?"":obj.getYpbh());
                map.put("PL1_ypbh2", StringUtils.isEmpty(obj.getYpbh())?"":obj.getYpbh());
                map.put("PL1_ypmc", StringUtils.isEmpty(obj.getYpmc())?"":obj.getYpmc());
                map.put("PL1_ggxh", StringUtils.isEmpty(obj.getGgxh())?"":obj.getGgxh());
                map.put("PL1_wtdw", StringUtils.isEmpty(obj.getWtdw())?"":obj.getWtdw());
                map.put("PL1_ypdj", StringUtils.isEmpty(obj.getYpdj())?"":obj.getYpdj());
                map.put("PL1_jylx", getCodes(obj.getJylx(),"jylx"));
                map.put("PL1_ypzt", StringUtils.isEmpty(obj.getYpzt())?"":obj.getYpzt());

                /*int p2_ypsl = 0 ;
                if(!StringUtils.isEmpty(obj.getBysl())){
                    p2_ypsl +=Integer.valueOf(obj.getBysl());
                }
                if(!StringUtils.isEmpty(obj.getJysl())){
                    p2_ypsl +=Integer.valueOf(obj.getJysl());
                }
                map.put("PL1_ypsl", p2_ypsl==0?"/":p2_ypsl+"");*/
                map.put("PL1_yjsl", StringUtils.isEmpty(lz.getNumber())?"":lz.getNumber());
                map.put("PL1_jhwcqx", StringUtils.isEmpty(lz.getJhwcqx())?"":DateUtil.StringFormat(lz.getJhwcqx(),"yyyy年MM月dd日"));
                map.put("PL1_jyyj", StringUtils.isEmpty(obj.getJyyj())?"":obj.getJyyj());
                map.put("PL1_jyxm", StringUtils.isEmpty(obj.getJyxm())?"":obj.getJyxm());
                map.put("PL1_jsyprq", StringUtils.isEmpty(lz.getStatusAt())?"":DateUtil.StringFormat(lz.getStatusAt(),"yyyy年MM月dd日"));
                map.put("PL1_jywcrq", StringUtils.isEmpty(lz.getJywcrq())?"":DateUtil.StringFormat(lz.getJywcrq(),"yyyy年MM月dd日"));
                map.put("PL1_byczqk", StringUtils.isEmpty(lz.getByczqk())?"":lz.getByczqk());
                if(lzList.size()>count){
                    String bz = lzList.get(count).getSpyj();
                    map.put("PL1_bz", StringUtils.isEmpty(bz)?"":bz);
                }
                map.put("PL1_count","第"+convert(count)+"联");

                if(StringUtils.isNotBlank(lz.getNextsprIds())) {
                    Sys_user slrUser = sysUserService.fetch(lz.getNextsprIds());
                    String fileId = slrUser.getFileId();
                    if (!StringUtils.isEmpty(fileId)) {
                        BusinessFileInfo signatureImage = businessFileInfoService.fetch(fileId);
                        //map.put("PL1_jsr",Globals.AppFileDomain+ Globals.AppUploadBase+signatureImage.getFilePath());
                        //map.put("PL1_jsr","C:/Users/allen/Desktop/docs/image/20240304/s8g9ko1mlkhimqm1mp1psamj4h.png");
                        map.put("PL1_jsr",uploadPath+signatureImage.getFilePath());
                    }
                    Sys_unit unit = sysUnitService.fetch(slrUser.getUnitid());
                    map.put("PL1_jyks", unit.getName());
                }
                listMap.add(map);
                count ++;
            }
            DocUtils.FileToFileLzd(demoAgreement,newAgreement,listMap);

            BusinessFileInfo report = new BusinessFileInfo();
            report.setInfoName(fileName);
            report.setInfoVersion(date);
            report.setInfoType("report");
            report.setRemark("");
            report.setOperatorName(StringUtil.getPlatformUsername());
            report.setFileType(".docx");
            report.setDisabled(false);
            report.setFilePath(newAgreementPath);
            report.setFileName(fileName);
            report.setFileBeforeName( fileName+".docx");
            report.setFileUrl(newAgreement);
            businessFileInfoService.insert(report);
            return Result.success("生成成功！").addData(newAgreement);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("system.error");
        }
    }

    public String getNames(String ids){
        String names ="";
        if(!StringUtils.isEmpty(ids)){
            String[] id = ids.split(",");
            for(int i = 0 ; i <id.length ;i++){
                names += sysDictService.getNameById(id[i]);
                if(i<(id.length-1)){
                    names+="/";
                }
            }
        }
        return names;
    }
    public String getCodes(String ids,String parentCode){
        String names ="";
        if(!StringUtils.isEmpty(ids)){
            String[] id = ids.split(",");
            for(int i = 0 ; i <id.length ;i++){
                names += sysDictService.getNameByCode(id[i],parentCode);
                if(i<(id.length-1)){
                    names+="/";
                }
            }
        }
        return names;
    }
    private String getUploadPathConfig() throws Exception {
        String uploadPath;
        //系统没开启配置,上传到项目路径
        if ("false".equals(Globals.MyConfig.getOrDefault("IsConfigUploadPath", "false"))){
            uploadPath= UploadController.class.getClassLoader().getResource("").getPath()+"upload";
        }else if (
                ("true".equals(Globals.MyConfig.getOrDefault("IsConfigUploadPath", "false")))&&(Globals.MyConfig.getOrDefault("ConfigUploadPath", null)!=null)
        ){
            uploadPath=Globals.MyConfig.get("ConfigUploadPath").toString();
        }else {
            throw new Exception("文件上传路径配置有误");
        }
        return uploadPath;
    }

    public static String convert(int number) {
        if(number <= 0){
            return "";
        }
        if(number == 1){
            return "一";
        }
        //数字对应的汉字
        String[] num = {"一", "二", "三", "四", "五", "六", "七", "八", "九"};
        //单位
        String[] unit = {"", "十", "百", "千", "万", "十", "百", "千", "亿", "十", "百", "千", "万亿"};
        //将输入数字转换为字符串
        String result = String.valueOf(number);
        //将该字符串分割为数组存放
        char[] ch = result.toCharArray();
        //结果 字符串
        String str = "";
        int length = ch.length;
        for (int i = 0; i < length; i++) {
            int c = (int) ch[i] - 48;
            if (c != 0) {
                str += num[c - 1] + unit[length - i - 1];
            }
        }
        if(number < 20 && number > 9){
            str = str.substring(1);
        }
        //System.out.println(str);
        return str ;
    }
}
